package com.example.emos.api.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.emos.api.common.util.PageUtils;
import com.example.emos.api.controller.form.ReturnScoreForm;
import com.example.emos.api.controller.form.TaskForm;
import com.example.emos.api.controller.form.UpdateTimeForm;
import com.example.emos.api.db.dao.TbExamineeDao;
import com.example.emos.api.db.dao.TbMarkDao;
import com.example.emos.api.service.MarkService;
import io.swagger.v3.core.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author ：Supyo
 * @date ：Created in 2021/11/16 15:03
 * @description：
 */
@Service
public class MarkServiceImpl implements MarkService {

    @Autowired
    TbMarkDao markDao;

    @Autowired
    TbExamineeDao examineeDao;


    @Override
    public PageUtils selectMarkBypages(HashMap param) {
        ArrayList<HashMap> list = markDao.selectMarkBypages(param);
        long count = markDao.count(param);
        int start = (Integer) param.get("start");
        int length = (Integer) param.get("length");
        PageUtils pageUtils = new PageUtils(list, count, start, length);


        //判断考核开始和结束区间
        //当前时间
        LocalDateTime time = LocalDateTime.now().withNano(0);
        System.out.println(time);
        for (int i = 0; i < list.size(); i++) {
            //获取考核时间
            LocalDateTime startTime[] = new LocalDateTime[list.size()];
            startTime[i] = (LocalDateTime) list.get(i).get("start_time");
            LocalDateTime endTime[] = new LocalDateTime[list.size()];
            endTime[i] = (LocalDateTime) list.get(i).get("end_time");
            int Status[] = new int[list.size()];
            Status[i] = (int) list.get(i).get("status");
            System.out.println(Status[i]);
            if (Status[i] != 2) {
                if (time.isAfter(startTime[i]) && time.isBefore(endTime[i])) {
                    int status = 1;
                    markDao.updateStatus((int) list.get(i).get("id"), status);
                }
                if (time.isBefore(startTime[i])) {
                    int status = 3;
                    markDao.updateStatus((int) list.get(i).get("id"), status);
                }
                if (time.isAfter(endTime[i])) {
                    int status1 = 4;
                    markDao.updateStatus((int) list.get(i).get("id"), status1);
                }
            }
        }
        return pageUtils;
    }

    @Override
    public HashMap task(TaskForm form) {
        HashMap map = markDao.task(form.getMarkId());
        int examId = (int) map.get("exam_id");
        int templateId = markDao.selectExamTemplate(examId);
        System.out.println("templateId: " + templateId);
        //根据考核模板Id查询试卷
        Object options = markDao.paper(templateId);
        System.out.println("options: " + options);

        int userId = (int) map.get("person_id");
        String roles = markDao.selectRoles(userId);
        map.put("options", options);

        map.put("roles", roles);
        return map;
    }

    @Override
    public int returnScore(ReturnScoreForm form) {
        int weight = markDao.weight(form.getMarkId());
        double totalScore = 0.01 * weight * form.getScore();
        BigDecimal b = new BigDecimal(totalScore);
        totalScore = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        Object options = JSONUtil.parseArray(form.getOptions()).toString();
        markDao.updateOptions(form.getMarkId(), options);
        int rows = markDao.returnScore(form.getMarkId(), form.getScore(), totalScore);

        //设置总分
        //查询exam_examineeId
        int examId = markDao.examId(form.getMarkId());
        int personId = markDao.person(form.getMarkId());

        //查询分数
        double sumScore = 0;
        double[] score = markDao.countSum(examId, personId);
        for (int i = 0; i < score.length; i++) {
            System.out.println(score[i]);
            sumScore += score[i];
        }

        //查询评级rate
        String rate = "";
        int templateId = markDao.selectExamTemplate(examId);
        System.out.println("templateId: " + templateId);

        int rankId = examineeDao.selectRankId(templateId);
        System.out.println("rankId: " + rankId);

        String rank = examineeDao.selectRank(rankId);
        System.out.println("rank: " + rank);

        JSONArray jsonArray = new JSONArray(rank);
        String garade[] = new String[jsonArray.size()];
        String minScore[] = new String[jsonArray.size()];
        String maxScore[] = new String[jsonArray.size()];
        int minscore[] = new int[jsonArray.size()];
        int maxscore[] = new int[jsonArray.size()];
        for (int i = 0; i < garade.length; i++) {
            garade[i] = (String) jsonArray.getJSONObject(i).get("grade");
            minScore[i] = (String) jsonArray.getJSONObject(i).get("minScore");
            maxScore[i] = (String) jsonArray.getJSONObject(i).get("maxScore");
            minscore[i] = Integer.parseInt(minScore[i]);
            maxscore[i] = Integer.parseInt(maxScore[i]);
            System.out.println("garade: " + garade[i]);
            System.out.println("minScore: " + minscore[i]);
            System.out.println("maxScore: " + maxscore[i]);
            if (sumScore >= minscore[i] && sumScore <= maxscore[i]) {
                rate = garade[i];
            }
        }


        markDao.updateScore(sumScore, examId, personId, rate);
        return rows;
    }

    @Override
    public int updateTime(UpdateTimeForm form) {
        int examId = form.getExamId();
        DateTime startTime = form.getStartTime();
        DateTime endTime = form.getEndTime();
        int rows = markDao.updateTime(form.getStartTime(), form.getEndTime(), examId);
        //判断状态
        DateTime time = DateTime.now();
        int status = 0;
        int status1 = 0;
        if (time.isAfter(startTime) && time.isBefore(endTime)) {
            status = 2;
            status1 = 1;
        }
        if (time.isBefore(startTime)) {
            status = 1;
            status1 = 3;
        }
        if (time.isAfter(endTime)) {
            status = 3;
            status1 = 4;
        }
        markDao.updateExamStatus(examId, status);
        List markID = markDao.selectMarkId(examId);

        for (int i = 0; i < markID.size(); i++) {
            markDao.updateStatus((Integer) markID.get(i), status1);
        }
        return rows;
    }

    @Override
    public int getTotalTask(int userId) {
        int count = markDao.getTotalTask(userId);
        return count;
    }
}
